"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "./auth-provider";
export interface WithProtectedRouteProps {
  children?: React.ReactNode;
}

type WrappedComponentType<P = {}> = React.ComponentType<P>;

export const withProtectedRoute = <P extends WithProtectedRouteProps>(
  WrappedComponent: WrappedComponentType<P>,
) => {
  const WithAuth = (props: P) => {
    const router = useRouter();
    const authsession = useAuth();
    const [isLoading, setIsLoading] = useState(true);
    useEffect(() => {
      const checkAuth = async () => {
        if (!authsession?.user) {
          router.push("/auth/login");
        } else {
          setIsLoading(false);
        }
      };

      checkAuth();
    }, [router, authsession]);
    if (isLoading) return <div>Page loading...</div>;
    return authsession?.user ? (
      <WrappedComponent {...props} />
    ) : (
      <div>auth deny</div>
    );
  };

  WithAuth.displayName = `WithProtectedRoute(${WrappedComponent.displayName || WrappedComponent.name || "Component"})`;

  return WithAuth;
};
